import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QComboBox, QLabel


class MyWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        layout = QVBoxLayout()

        # 创建 QComboBox 实例
        self.combo_box = QComboBox(self)

        # 添加文本和对应的值
        self.combo_box.addItem("苹果", 1)
        self.combo_box.addItem("香蕉", 2)
        self.combo_box.addItem("橙子", 3)

        # 设置默认选项
        self.combo_box.setCurrentIndex(0)

        # 创建标签用于显示选中项的值
        self.label = QLabel(f"你选择的值是: {self.combo_box.itemData(self.combo_box.currentIndex())}", self)

        # 连接信号和槽函数
        self.combo_box.currentIndexChanged.connect(self.on_combo_box_changed)

        layout.addWidget(self.combo_box)
        layout.addWidget(self.label)
        self.setLayout(layout)

        self.setWindowTitle('QComboBox 文本和值不同示例')
        self.setGeometry(300, 300, 300, 200)

    def on_combo_box_changed(self, index):
        # 获取当前选中项的值
        value = self.combo_box.itemData(index)
        self.label.setText(f"你选择的值是: {value}")


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MyWindow()
    window.show()
    sys.exit(app.exec_())